#!/bin/bash

set -Eeuo pipefail
shopt -s inherit_errexit

# expects the following variables defined in the environment:
# - GITLAB_PROJECT_URL: git repo without protocol
# - GITLAB_FORK_URL: fork of the git repo without protocol
# - GITLAB_TOKEN: GitLab private token with access to the git repo
# - BRANCH_NAME: branch name in the fork of the git repo
# - SOURCE_BRANCH_NAME: source branch name to checkout, by default `main`
# - GIT_USER_NAME: Git user name
# - GIT_USER_EMAIL: Git user email

# shellcheck disable=SC1091
. cki_utils.sh

BASE_DIR=$(mktemp -d)
trap 'rm -rf "${BASE_DIR}"' EXIT

DATA_PATH="${BASE_DIR}/repo"
mkdir -p "${DATA_PATH}"
cd "${DATA_PATH}"

cki_echo_yellow "Fetching repository..."
if ! [[ -d .git ]]; then
    # shellcheck disable=SC2154
    git clone "https://ignored:${GITLAB_TOKEN}@${GITLAB_PROJECT_URL}.git/" .
    cki_echo_green "  successfully cloned main repository"
    # shellcheck disable=SC2154
    git remote add fork "https://ignored:${GITLAB_TOKEN}@${GITLAB_FORK_URL}.git/"
    # shellcheck disable=SC2154
    git config user.name "${GIT_USER_NAME}"
    # shellcheck disable=SC2154
    git config user.email "${GIT_USER_EMAIL}"
fi
git fetch --all
cki_echo_green "  successfully fetched updates"

# shellcheck disable=SC2154
cki_echo_yellow "Checking out '${BRANCH_NAME}'"
if git show-ref --verify --quiet "refs/remotes/fork/${BRANCH_NAME}"; then
    git switch --track "fork/${BRANCH_NAME}"
    git reset --hard "fork/${BRANCH_NAME}"
    cki_echo_green "  switched to branch"
    if ! git rebase origin/HEAD; then
        cki_echo_yellow "  rebased failed, reverting to upstream version"
        git rebase --abort || true
        git reset --hard "origin/HEAD"
    else
        cki_echo_green "  rebased to origin/HEAD"
    fi
else
    git checkout --track "origin/${SOURCE_BRANCH_NAME:-main}" -b "${BRANCH_NAME}"
    git config "branch.${BRANCH_NAME}.merge" "refs/heads/${BRANCH_NAME}"
    git config "branch.${BRANCH_NAME}.remote" fork
    cki_echo_green "  created branch"
fi

cki_echo_yellow "Updating ystream composes"
# shellcheck disable=SC2154
if python3 -m cki_tools.update_ystream_composes update; then
    cki_echo_green "  completed"
    exit_code=0
else
    cki_echo_red "  failed, but trying to continue"
    exit_code=1
fi

cki_echo_yellow "Checking for changes"
git add .
if ! git diff --stat --cached --exit-code; then
    timestamp=$(date +'%F %H:%M')
    git commit -m "Automatic compose updates as of ${timestamp}"
    git push \
        --force \
        --push-option merge_request.create \
        --push-option merge_request.title="Automatic compose updates" \
        --push-option merge_request.remove_source_branch \
        fork
    cki_echo_green "  committed and pushed changes"
elif ! git log origin/"${BRANCH_NAME}" ^HEAD --quiet --exit-code; then
    cki_echo_green "  updating rebased branch"
    git push --force
else
    cki_echo_green "  no changes found"
    exit "${exit_code}"
fi

mr_id=$(gitlab \
    --private-token "${GITLAB_TOKEN}" \
    --output json \
    project-merge-request list \
    --project-id "${GITLAB_PROJECT_URL#*/}" \
    --source-branch "${BRANCH_NAME}" |
    jq '.[0].iid'
)

cki_echo_yellow "Updating MR description"
#shellcheck disable=SC2016
updated_composes=$(git show | sed -n 's/^+.*distro_name = "\(.*\)".*/- `\1`/p')
description_footer=$(python3 -m cki_lib.footer --format gitlab --what updated)
gitlab \
    --private-token "${GITLAB_TOKEN}" \
    project-merge-request update \
    --project-id "${GITLAB_PROJECT_URL#*/}" \
    --iid "${mr_id}" \
    --description $'Updated composes:\n'"${updated_composes}${description_footer}"
cki_echo_green "  done"

cki_echo_yellow "Triggering the bot"
# shellcheck disable=SC2154
comment_body=$(python3 -m cki_lib.yaml dump --format json < "${YSTREAM_COMPOSES_CONFIG_PATH}" | jq -r '.[".bot_comment"]')
comment_footer=$(python3 -m cki_lib.footer --format gitlab)
gitlab \
    --private-token "${GITLAB_TOKEN}" \
    project-merge-request-note create \
    --project-id "${GITLAB_PROJECT_URL#*/}" \
    --mr-iid "${mr_id}" \
    --body " ${comment_body}${comment_footer}"  # space before body otherwise a starting '@' means read-from-file
cki_echo_green "  done"

exit "${exit_code}"
